
export function useCountdown(count) {
  // 记录当前的数字
  const currentCount = ref(count);
  // 记录是否开始倒计时了
  const isStart = ref(false);
  let timerId;

  function clear() {
    timerId && clearInterval(timerId);
  }

  function stop() {
    isStart.value = false;
    clear();
    timerId = null;
  }

  function reset() {
    currentCount.value = count;
    stop();
  }

  function start() {
    if (unref(isStart) || !!timerId) {
      return;
    }

    isStart.value = true;
    timerId = setInterval(() => {
      if (unref(currentCount) === 1) {
        // 计时结束，恢复初始
        reset();
      } else {
        currentCount.value -= 1;
      }
    }, 1000);
  }

  function restart() {
    reset();
    start();
  }

  return { start, reset, restart, clear, stop, currentCount, isStart };
}
